<?php

//defined('BASEPATH') OR exit('No direct script access allowed');
class Shop extends MY_Test
{
    public function __construct()
    {
        parent::__construct();
        $this->load->service('user/user_service');
    }

    //    protected 或 _开头的 不能被请求

    public function index()
    {
        //        echo 'i am shop controller';
//        $data['item'] = ['title' => 'data3333', 'body' => 'helloworld'];
//        $this->load->view('shop/shop', $data);
        while (true) {


            $order_id = $this->input->get_post('order_id') ?? 88;

            $this->load->model('my_order');
//        print_r($this->My_order);exit;
            $id = $this->my_order->insert_entry($order_id);
            echo '{"order_id": ' . $id . ', "error": 0}';
        }
    }

    public function test1($name, $id)
    {
        echo 'test';
        echo $name;
        echo $id;
    }

    public function test2()
    {
        $this->load->model('crm_custom');
        $res = $this->crm_custom->get_last_ten_entries();
        dump($res);
    }

    public function test3()
    {
        //        $string = $this->load->view('shop/shop', '', TRUE);//只返回不显示
        //        file_put_contents('aaa',$string);ƒ
        $this->load->vars('aaa', '我是aaa');
        $this->load->view('shop/shop');
    }

    public function test4($id)
    {
        echo $id;
        dump($this->uri->segment(3));//用于获取某一段的值
        dump($this->input);//用于获取某一段的值

        dump($this->input->post());
        dump($this->input->server('DOCUMENT_ROOT'));
        $this->load->helper('array');
        dump($this->load);
    }

    public function test5()
    {
        //1.直接
        //装载数据库操作类到超级对象,默认属性是db
        $this->load->database();
        //        dump($this->db);
        $sql = "SELECT * FROM `advisory` LIMIT 10";
        $res = $this->db->query($sql);//返回对象
        //        dump($res->result());//是一个个对象
        $data['user_list'] = $res->result();//返回对象
        $data['user_list'] = $res->result_array();//返回数组
        $data['user_list'] = $res->row();//返回第一个对象
        $this->load->view('test5', $data);

        echo ENVIRONMENT;


    }

    public function test6()
    {
        $sql = "INSERT INTO `b2b`.`advisory` (`id`, `name`, `mobile_phone`, `company_name`, `linkMen`, `remark`, `created`) VALUES (NULL, 'heven', '15291181898', '铱云科技', NULL, NULL, '2017-10-12 16:37:19')";

        $bool = $this->db->query($sql);
        if ($bool) {
            echo $this->db->affected_rows();
            echo $this->db->insert_id();
        } else {
            echo 'no';
        }
    }

    public function test7()
    {
        //        $name = $this->input->post('name');
        //        $pass = 'abbcc';
        $data = [  //只支持一个数组
            'lili',
            '123'
        ];
        $sql = "INSERT INTO advisory (name, mobile_phone) VALUE (?,?)";
        $bool = $this->db->query($sql, $data);
        if ($bool) {
            echo $this->db->affected_rows();
            echo $this->db->insert_id();
        } else {
            echo 'no';
        }
    }


    public function test8()
    {
        //2.AR模型 model
        //1.查询
        //        $res = $this->db->get('advisory');//返回结果集对象
        //        dump($res);
        //        foreach ($res->result() as $r) {
        //            echo $r->id;
        //        }

        //2.insert
        $data = [
            'name' => 'adfddafa',
            'mobile_phone' => 33333
        ];
        $bool = $this->db->insert('advisory', $data);
        if ($bool) {
            echo $this->db->affected_rows();
            echo $this->db->insert_id();
        } else {
            echo 'no';
        }

        //3.update
        $data = [
            'name' => 'adfddafa',
            'mobile_phone' => 8888
        ];
        $bool = $this->db->update('advisory', $data, ['id' => $this->db->insert_id()]);
        dump($bool);

        //4.delete
        $this->db->delete('advisory', ['id' => 1054]);

        //5.连贯操作
        $res = $this->db->select('id,name')
            ->from('advisory')
            ->where('id >=', 1054)//一定要空格,正则匹配的
            ->order_by('id desc')
            ->limit(3, 2)//这个和mysql是反的,跳过2条取3条
            ->get();
        //        echo $this->db->get_compiled_select();//SELECT `id`, `name` FROM `advisory` WHERE `id` >= 1054 ORDER BY `id` desc LIMIT 3, 2
        dump($res->result());

        //显示最近一条
        echo $this->db->last_query();

        //条件
        //        $res = $this->db->where('name','adfddafa')->get('advisory');
        $res = $this->db->where([
            'name' => 'adfddafa',
            'id >' => 1063
        ])->get('advisory');

        dump($res->result());
    }

    public function test9()
    {
        $this->load->model('advisory');
        dump($this->advisory->getAll());
    }

    public function test10()
    {
        $this->load->library('Aes', ['name' => 'bbbb']);
        $this->aes->test();

        $this->load->helper('my_fun');
        test();
    }

    public function test11()
    {
        $this->load->helper('url');
        $this->load->view('test11');
    }

    public function test12($id)
    {
        echo $id;
    }

    public function test13()
    {

        //分页
        $this->load->library('pagination');
        $this->load->helper('url');
        $page_size = 10;
        $config = [
            'base_url' => 'http://www.ci3.net/shop/test13',//site_url('shop/test13');
            'total_rows' => 200,
            'per_page' => $page_size,
            'first_link' => '首页',
            'next_link' => '下一页',
            'prev_link' => '上一页',
            'last_link' => '末页'
        ];

        //添加额外属性
        //        $config['attributes'] = array('class' => 'myclass');


        $this->pagination->initialize($config);
        $data['links'] = $this->pagination->create_links();//

        $offset = intval($this->uri->segment(3));

        $sql = "select * from advisory LIMIT $offset,$page_size";
        $data['res'] = $this->db->query($sql)->result();

        $this->load->view('test13', $data);

    }

    public function test14()
    {
        //file
        $this->load->helper('url');
        echo 'base_url:' . base_url('shop/test15') . '<br>';
        echo 'site_url:' . site_url('shop/test15') . '<br>';
        echo 'APPPATH:' . APPPATH . '<br>';
        $this->load->view('test14');
    }

    public function test15()
    {
        //        dump($constant = get_defined_constants(true));
        //        echo $constant['data']
        //        $this->load->helper('file');
        $uploads_path = APPPATH . 'uploads';
        if (!file_exists($uploads_path)) { //可以抽像成函数
            mkdir($uploads_path);
            $old = umask(0);
            chmod($uploads_path, 0755);
            umask($old);//&& chmod($uploads_path,777);
        }

        $config['upload_path'] = $uploads_path;
        $config['allowed_types'] = 'gif|jpg|png|rar';
        $config['file_name'] = uniqid();
        //        $config['max_size']     = 100;//kb
        //        $config['max_width']        = 1024;
        //        $config['max_height']       = 768;

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('pic')) {
            $error = ['error' => $this->upload->display_errors()];
            //            $this->load->view('upload_form', $error);
            print_r($error);
        } else {
            $data = ['upload_data' => $this->upload->data()];
            //            $this->load->view('upload_success', $data);
            print_r($data);
        }
    }


    public function test16()
    {
        //        核心(这个不用load) 扩展 辅助
        //        log_message(1,'aaaabbb');
        //        exit;
        $this->load->library('session');
        $user = [
            'id' => 3,
            'name' => 'jack'
        ];
        $user = new stdClass();
        $user->name = 'abc';
        $user->age = 111;
        $this->session->set_userdata('user', $user);
        var_dump($this->session->userdata('user'));

        log_message('error', 'aaaa');
        //        $this->session->flashdata();
        //        $this->session->set_flashdata()
        //只取一次
    }

    public function test17()
    {
        $tree = new \algo\BinaryTree();
        //        dump($tree);
        //验证码
        $file = fopen(APPPATH . 'logs/log-' . date('Y-m-d') . '.php', 'r');
        //        print_r($file);
        $pattern = '/-->(.*)$/';
        while (!feof($file)) {
            $line = fgets($file);
            if (preg_match($pattern, $line, $match)) {
                $node = new \algo\Node($match[1]);
                $tree->insert($node);
            }
        }
        fclose($file);

        $pir = new \SplPriorityQueue();
        $tree->preOrder(function ($node) use ($pir) {
            //            echo $node->value . ' ' . $node->count . '<br>';
            $pir->insert($node->value, $node->count);
        });

        echo "COUNT->" . $pir->count() . "<br/>";

        //mode of extraction
        $pir->setExtractFlags(\SplPriorityQueue::EXTR_BOTH);

        //Go to TOP
        $pir->top();

        while ($pir->valid()) {
            print_r($pir->current());
            echo "<br/>";
            $pir->next();
        }
    }

    public function test18()
    {
        //连续出现的最大长度
        $file = fopen(APPPATH . 'logs/log-' . date('Y-m-d') . '.php', 'r');
        //        print_r($file);
        $pattern = '/-->(.*)$/';

        $arr = [];
        while (!feof($file)) {
            $line = fgets($file);
            if (preg_match($pattern, $line, $match)) {
                $arr[] = $match[1];
            }
        }
        fclose($file);

        $length = count($arr);
        $l = 0;
        $r = 0;
        $max = 0;
        $res = '';
        while ($l < $length) {
            if ($r + 1 < $length && $arr[$l] == $arr[$r]) {//考虑越界问题
                $r++;
            } else {
                $l++;
            }

            if ($r - $l > $max) {
                $max = $r - $l;
                $res = $arr[$l];
            }
            //            $max = max($r-$l,$max);

        }

        echo 'l:' . $l . "<br>";
        echo 'r:' . $r . "<br>";
        echo 'max:' . $max . "<br>";
        echo '$res:' . $res . "<br>";
        //        print_r($key);
    }

    public function test19()
    {
        //连续出现的最大长度
        $file = fopen(APPPATH . 'logs/log-' . date('Y-m-d') . '.php', 'r');
        //        print_r($file);
        $pattern = '/-->(.*)$/';

        $l = 0;
        $r = 0;
        $max = 0;
        $begin = fgets($file);
        $begin = fgets($file);
        $begin = fgets($file);
        preg_match($pattern, $begin, $match);
        $begin = $match[1];
        //        echo $begin;
        $res = '';
        $arr[] = $begin;
        while (!feof($file)) {
            $line = fgets($file);
            if (preg_match($pattern, $line, $match)) {
                $cur = $match[1];
                $arr[] = $cur;
            }

            if ($arr[$l] == $arr[$r]) {//考虑越界问题
                $r++;
            } else {
                $l++;
            }

            //如果长度大于N的就放到里面


            if ($r - $l > $max) {
                $max = $r - $l;
                $res = $arr[$l];

            }
        }
        fclose($file);

        dump($arr);
        echo 'l:' . $l . "<br>";
        echo 'r:' . $r . "<br>";
        echo 'max:' . $max . "<br>";
        echo '$res:' . $res . "<br>";
    }

    public function test20()
    {
        //验证码
        $this->load->helper('captcha');

        create_folder('./captcha');
        $vals = [
            'word' => rand(1000, 9999),//'Random word',
            'img_path' => './captcha/',
            'img_url' => '/captcha/',
            //            'font_path' => './path/to/fonts/texb.ttf',
            'img_width' => 100,
            'img_height' => 30,
            'expiration' => 7200,
            //            'word_length'   => 8,
            //            'font_size' => 16,
            //            'img_id'    => 'Imageid',
            //            'pool'      => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',

            // White background and border, black text and red grid
            'colors' => [
                'background' => [255, 255, 255],
                'border' => [255, 255, 255],
                'text' => [0, 0, 0],
                'grid' => [255, 40, 40]
            ]
        ];

        $cap = create_captcha($vals);
        session_start();
        $_SESSION['cap'] = $cap['word'];
        echo $cap['word'];//放session
        echo $cap['image'];
        echo ini_get('session.save_path');

    }

    public function test21()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('name', '用户名', 'required');
        $bool = $this->form_validation->run();
        var_dump($bool);
    }

    public function test22()
    {
        new \Abc\def();
        $this->user_service->login('kui');
    }

    public function test23()
    {
        $arr = [
            '333',
            'abc'
        ];

        array_walk($arr, function (& $value) {
            $value = "'$value'";
        });
        print_r(implode(",", $arr));
    }

    public function test24($userId = 0, $pageNum = 1, $pageSize = 10, $source = '', $videoPage = 1)
    {
        $method = 'POST';
        $url = 'http://10.222.18.226:8080/as/index/recommend';
        $headers = ['Content-Type' => 'application/json'];
        $body = [
            'userId' => $userId,
            'pageNum' => $pageNum,
            'pageSize' => $pageSize,
            'source' => $source,
            'videoPage' => $videoPage
        ];
        $client = new GuzzleHttp\Client();
        $res = $client->request($method, $url, ['json' => $body]);
//        $client->request('post',$url,['form_params'=>$params,'verify'=>false]);//关闭https验证

//        print_r($res);
//        exit;
//        print_r($res->getStatusCode());// "200"
//        print_r($res->getHeader('content-type'));// 'application/json; charset=utf8'
//        print_r($res->getBody()->read(1000));// {"type":"User"...'

        dump(json_decode($res->getBody(), true));

    }

    public function test25()
    {

        $this->benchmark->mark('code_start');

// Some code happens here
        for ($i = 0; $i < 10000000; $i++) {

        }

        $this->benchmark->mark('code_end');

        echo $this->benchmark->elapsed_time('code_start', 'code_end');

        $this->benchmark->mark('dog');

// Some code happens here

        $this->benchmark->mark('cat');

// More code happens here

        $this->benchmark->mark('bird');

        echo $this->benchmark->elapsed_time('dog', 'cat');
        echo $this->benchmark->elapsed_time('cat', 'bird');
        echo $this->benchmark->elapsed_time('dog', 'bird');

    }


    public function test26()
    {
        print_r($this->config->load('java_team'));
        print_r($this->config->item('topic_url'));

        $topicInfo['topic_address'] = '上海讪,方吴,我不';
        print_r(explode(',', $topicInfo['topic_address']));
        $topicInfo['topic_address'] = explode(',', $topicInfo['topic_address'])[0];

        echo $topicInfo['topic_address'];
    }

    public function test27()
    {
        $redis = new Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->set('ab', 'cccc');
        echo $redis->get('ab');
    }

    public function test28()
    {
        $this->load->library('RedisBiz');
        var_dump($this->redisbiz);
        $this->redisbiz->hset('user1', 'name', 'vincent');

        echo $this->redisbiz->hget('user1', 'name');
    }

    public function test29()
    {
        abc();
        echo __METHOD__;
        log_message('info', 'abbb');
    }

    public function test30()
    {
//        error_reporting(E_ALL ^ E_NOTICE);
//        error_reporting(E_ALL);
//        echo $notice;
//        abc();
//        print_r(ini_get_all());
        echo time();
    }

    public function test31()
    {
//        print_r($this->config->load('redis'));
        $config = $this->config->item('redis');
//        $this->load->library('Datasource');
//        $this->load->library('RedisHelper');
        require_once APPPATH . 'third_party/Datasource.php';
        require_once APPPATH . 'third_party/RedisHelper.php';
//        print_r(Datasource::getRedis($config));
        $redis_obj = Datasource::getRedis();
//        foreach ($goods as $i => $goods_id) {
//            $d_list[] = 'info_g_' . $goods_id;  // 商品详情
//        }
        $data_list = $redis_obj->set('abcd', '88888999');
        echo $redis_obj->get('abcd');
    }

    public function test32()
    {
//    use Endroid\QrCode\QrCode;

        $qrCode = new \Endroid\QrCode\QrCode('Life is too short to be generating QR codes');

        header('Content-Type: ' . $qrCode->getContentType());
        echo $qrCode->writeString();

        /**
         * 高级用法
         * use Endroid\QrCode\ErrorCorrectionLevel;
         * use Endroid\QrCode\LabelAlignment;
         * use Endroid\QrCode\QrCode;
         * use Endroid\QrCode\Response\QrCodeResponse;
         *
         * // Create a basic QR code
         * $qrCode = new QrCode('Life is too short to be generating QR codes');
         * $qrCode->setSize(300);
         *
         * // Set advanced options
         * $qrCode->setWriterByName('png');
         * $qrCode->setMargin(10);
         * $qrCode->setEncoding('UTF-8');
         * $qrCode->setErrorCorrectionLevel(ErrorCorrectionLevel::HIGH);
         * $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
         * $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
         * $qrCode->setLabel('Scan the code', 16, __DIR__.'/../assets/fonts/noto_sans.otf', LabelAlignment::CENTER);
         * $qrCode->setLogoPath(__DIR__.'/../assets/images/symfony.png');
         * $qrCode->setLogoWidth(150);
         * $qrCode->setRoundBlockSize(true);
         * $qrCode->setValidateResult(false);
         *
         * // Directly output the QR code
         * header('Content-Type: '.$qrCode->getContentType());
         * echo $qrCode->writeString();
         *
         * // Save it to a file
         * $qrCode->writeFile(__DIR__.'/qrcode.png');
         *
         * // Create a response object
         * $response = new QrCodeResponse($qrCode);
         */
    }

    public function test33()
    {
        echo base64_decode('IGEgemEgYSB6YSBmaWdodGluZw==');
    }


    public function test34()
    {
        function abc($e, $f)
        {
            echo 'abc';
            echo $e;
            echo $f;
        }

        call_user_func('abc', 'edf', 'bcd');
    }

    public function test35()
    {
        echo config_item('notice_host');

        echo strip_tags('<h1>aaa</h1>');
    }

    public function test36()
    {
        $this->load->library('unit_test');
        $test = 1 + 1;

        $expected_result = 2;

        $test_name = 'Adds one plus one';

        print_r($this->unit->run($test, $expected_result, $test_name));
    }

    public function test37()
    {
        //抽奖函数
        function get_rand($proArr)
        {
            $result = '';

            //概率数组的总概率精度
            $proSum = array_sum($proArr);

            //概率数组循环
            foreach ($proArr as $key => $proCur) {
                $randNum = mt_rand(1, $proSum);
                if ($randNum <= $proCur) {
                    $result = $key;
                    break;
                } else {
                    $proSum -= $proCur;
                }
            }
            unset ($proArr);

            return $result;
        }

        $prize_arr = [
            '0' => ['id' => 1, 'prize' => '平板电脑', 'v' => 1],
            '1' => ['id' => 2, 'prize' => '数码相机', 'v' => 5],
            '2' => ['id' => 3, 'prize' => '音箱设备', 'v' => 10],
            '3' => ['id' => 4, 'prize' => '4G优盘', 'v' => 12],
            '4' => ['id' => 5, 'prize' => '10Q币', 'v' => 22],
            '5' => ['id' => 6, 'prize' => '下次没准就能中哦', 'v' => 50],
        ];

        foreach ($prize_arr as $key => $val) {
            $arr[$val['id']] = $val['v'];
        }

        $rid = get_rand($arr); //根据概率获取奖项id

        $res['yes'] = $prize_arr[$rid - 1]['prize']; //中奖项
        unset($prize_arr[$rid - 1]); //将中奖项从数组中剔除，剩下未中奖项
        shuffle($prize_arr); //打乱数组顺序
        for ($i = 0; $i < count($prize_arr); $i++) {
            $pr[] = $prize_arr[$i]['prize'];
        }
        $res['no'] = $pr;
        echo json_encode($res);
    }

    public function test38()
    {
        $ip = gethostbyname('www.csdn.net');
        $num_ip = ip2long($ip);
        echo $num_ip, '<br/>';
        echo long2ip($num_ip);
    }

    public function test39()
    {
        /*
 * 下划线转驼峰
 */
        function convertUnderline($str)
        {
            $str = preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) {
                return strtoupper($matches[2]);
            }, $str);
            return $str;
        }

        /*
         * 驼峰转下划线
         */
        function humpToLine($str)
        {
            $str = preg_replace_callback('/([A-Z]{1})/', function ($matches) {
                return '_' . strtolower($matches[0]);
            }, $str);
            return $str;
        }

        function convertHump(array $data)
        {
            $result = [];
            foreach ($data as $key => $item) {
                if (is_array($item) || is_object($item)) {
                    $result[humpToLine($key)] = convertHump((array)$item);
                } else {
                    $result[humpToLine($key)] = $item;
                }
            }
            return $result;
        }

        $res = convertUnderline('user_id');
        echo $res;


    }


    public function test40()
    {
        echo round(265 * 0.9);
    }

    public function test41()
    {
//        $path = APPPATH.'qrcode.jpg';
        $path = APPPATH . 'WX20180603-212358.png';
        echo $path;
        $qrcode = new \Zxing\QrReader($path);
        $text = $qrcode->text(); //return decoded text from QR Code
        echo $text;//http://weixin.qq.com/r/NXWuoQ3EpzPYhxzCnyAR
        //http://weixin.qq.com/r/NXWuoQ3EpzPYhxzCnyAR
    }

    public function test42()
    {
        function getImgHM($filename, $x = 8, $y = 8)
        {
            list($width, $height) = getimagesize($filename);
            $new_width = $x;
            $new_height = $y;
            $image_p = imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefromjpeg($filename);
            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            imagefilter($image_p, IMG_FILTER_GRAYSCALE);
            $result = '';
            For ($x = 0; $x < $new_width; $x++) {
                For ($y = 0; $y < $new_height; $y++) {
                    $P = getP($image_p, $x, $y);
                    $result = ($P + $result);
                }
            }
            $std = $result / ($new_width * $new_height);
            $HM = '';
            For ($x = 0; $x < $new_width; $x++) {
                For ($y = 0; $y < $new_height; $y++) {
                    $C = getP($image_p, $x, $y);
                    if ($C < $std) {
                        $HM .= 0;
                    } else {
                        $HM .= 1;
                    }
                }
            }
            imagedestroy($image_p);
            RETURN $HM;
        }

        function getP($image, $x, $y)
        {
            $Color_arr = imagecolorsforindex($image, imagecolorat($image, $x, $y));
            $P = ($Color_arr["red"] + $Color_arr["blue"] + $Color_arr["green"]) / 3;
            return $P;
        }

        function checkHM($search, $path)
        {
            $HM = getImgHM($search);
            $HM_2 = getImgHM($path);
            echo $search . ':' . $HM . '<br>' . $path . ':' . $HM_2 . '<br>';
            $diff = '';
            For ($i = 0; $i < 64; $i++) {
                if ($HM[$i] == $HM_2[$i]) {
                    $diff++;
                }
            }
            $diff = $diff / 64;
            echo $diff;
        }

        checkHM(APPPATH . 'pic(1).jpg', APPPATH . 'pic(2).jpg');
    }

    public function test43()
    {
        ini_set('memory_limit', '1024M'); //升级为申请256M内存
        // Load first image
        $image1 = Image::fromFile($path = APPPATH . 'pic(1).jpg');

        // Load second image to compare
        $image2 = Image::fromFile(APPPATH . 'pic(2).jpg');

        // If both images have an known background substract it
//        $mask = Image::fromFile('demo_inputs/mask.png');
//        $image1 = $image1->subtract($mask, 15); // use 15% tolerance
//        $image2 = $image2->subtract($mask, 15); // use 15% tolerance

        // Compare both images
        $equal = $image1->compare($image2); // Returns a boolean value whether these images are equal or not
        print_r($equal);
        // Or if you are interessted in how equal they are
        $diff = $image1->difference($image2); // Retuns a float between 1 and 0, where 1 is equal and 0 is total difference
        print_r($diff);
    }

    public function test44()
    {
        echo 'ip';
        var_dump(Zhuzhichao\IpLocationZh\Ip::find('171.12.10.156'));
    }

    public function test45()
    {
        //时间
        echo format_date(1408090874);
        fastcgi_finish_request();
    }

    public function test46()
    {
        echo $mqKey = ftok(__DIR__, 'a');
    }

    public function test47($concurrency = 50)
    {
        $em = '万人同擠獨木橋，再試一次吧～~ ';

        $limit = $concurrency; // 每秒的访问次数管理
        $mqKey = ftok(__DIR__, 'a');
        $mQueue = msg_get_queue($mqKey, 0666);
        if ($mQueue !== false) {
            $mqStat = msg_stat_queue($mQueue);
            print_r($mqStat);
            if ($mqStat['msg_qnum'] >= 40 || msg_send($mQueue, 1, microtime(true), false, false, $code)) {
                echo $limit;
                if ($mqStat['msg_qnum'] > $limit) {
                    $idx = $mqStat['msg_qnum'] - $limit;
                    echo $idx;
                    do {
                        $ret = msg_receive($mQueue, 0, $msgType, 32, $message, false, MSG_IPC_NOWAIT);
                        if ($ret && is_numeric($message) && (microtime(true) - $message) < 0.5) { // 每半秒的限制
                            $response = [
                                'success' => false,
                                'err' => [
                                    'em' => $em,
                                    'ec' => 509,
                                ],
                                'data' => $em,
                            ];
                            echo json_encode($response, JSON_FORCE_OBJECT);
                            exit;
                        }
                        $idx--;
                    } while ($idx > 0);
                }
            } elseif ($mQueue !== false && $code === 35) {
                msg_remove_queue($mQueue);
            }
        }

        $sapi_type = php_sapi_name();
        echo $sapi_type;
    }

    public function test48()
    {
        $redis = get_redis();

//        for($i=0;$i<100;$i++){
//            echo $i.$redis->get($i)."\n";
//
//        }

//        $redis->lpush('b', 333);
//        echo $redis->lpop('b');

//        send_kafka('log_message222', ['aeee' => 333113333113]);
//        $arr = consumer_kafka('log_message222');
//        print_r($arr);

//        var_dump(MyKafka::instance());
//        var_dump(MyKafka::instance());
//        var_dump(MyKafka::instance());
//        var_dump(MyKafka::instance());
//        var_dump(MyKafka::instance('log_message'));

//        $redis->hset('user:1:info','name','zzz');
//        $redis->hset('user:1:info','age',333);

//        print_r($redis->hgetall('user:1:info'));
//        print_r($redis->hkeys('user:1:info'));
//        print_r($redis->hvals('user:1:info'));

//        $redis->zadd('user',99,'rrr');
//        print_r($redis->zrange('user',0,-1,'WITHSCORES'));

    }

    public function test49()
    {
        echo 'test49';
        echo $str = 'a\aa';
        echo '<hr>';
        echo stripslashes($str);
    }

    public function test50()
    {
        $this->load->view('test50');
    }

    public function test51()
    {
        $host = ["userInfo:" . json_encode(['userId' => 123])];// 域名不帶http://
        $data = [
            'aa' => 'xx',
            'bb' => 'xx'
        ];
        $url = 'http://172.81.234.239:5678/demo1/topic/list';


        function curl_post($host, $data, $url)
        {
            $ch = curl_init();
            $res = curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_HEADER, 0);
//            curl_setopt($ch, CURLOPT_POST, 0);
//            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $host);
            $handles = curl_exec($ch);
            curl_close($ch);
            return $handles;
        }

//        var_dump(curl_post($host, $data, $url));
        $res = curl_post($host, $data, $url);
        $res = json_decode($res, true);
        $arr = json_decode(file_get_contents('http://172.81.234.239:8092/'), true);
        array_unshift($res, $arr);
//        print_r($res);
        echo json_encode($res);
//        '{"id":10,"title":"iphonex，全新","desc":"不错"}'

//        function postData($url, $post)
//        {
//            $ch = curl_init();
//            $timeout = 300;
//            curl_setopt($ch, CURLOPT_URL, $url);
//            curl_setopt($ch, CURLOPT_POST, true);
//            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
//            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //使用php curl获取页面内容或提交数据, 有时候希望返回的内容作为变量储存, 而不是直接输出
//            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);//在发起连接前等待的时间，如果设置为0，则无限等待。
//            $handles = curl_exec($ch);
//            curl_close($ch);
//            return $handles;
//        }
//
//        // 提交json 數據
//        function postData($url, $post)
//        {
//            $ch = curl_init();
//            curl_setopt($ch, CURLOPT_URL, $url);
//            curl_setopt($ch, CURLOPT_POST, true);
//            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
//            curl_setopt($ch, CURLOPT_HTTPHEADER, [
//                    'Content-Type:application/json',
//                    'Content-Length:' . strlen($post)]
//            );
//            $handles = curl_exec($ch);
//            curl_close($ch);
//            return $handles;
//        }
//
//
////刪除請求
//
////        $url = '********************';
////        $this->postData($url);
//
//        function postData($url)
//        {
//            $ch = curl_init();
//            curl_setopt($ch, CURLOPT_URL, $url);
//            curl_setopt($ch, CURLOPT_USERPWD, "guest:unknow44");
//            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, DELETE);
//            curl_setopt($ch, CURLOPT_HTTPHEADER, [
//                    'Content-Type:application/json']
//            );
//            $handles = curl_exec($ch);
//            curl_close($ch);
//            return $handles;
//        }

    }

    public function test52()
    {
//        print_r($_SERVER);

        $headers = [];
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
//                echo $name;
//                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
                $headers[] = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5))))) . ':' . $value;
            }
        }
//        array_merge()
        print_r($headers);
//        echo json_encode($headers);
//        $host = ["userInfo:".json_encode(['userId'=>123])];// 域名不帶http://
//        $url = 'http://localhost:5678/demo1/topic/list';
//
//
//
//        function curl_post($host, $data, $url)
//        {
//            $ch = curl_init();
//            curl_setopt($ch, CURLOPT_URL, $url);
//            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
//            curl_setopt($ch, CURLOPT_HEADER, 0);
//            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//            curl_setopt($ch, CURLOPT_HTTPHEADER, $host);
//            $handles = curl_exec($ch);
//            curl_close($ch);
//            return $handles;
//        }
//        $res = curl_post($host, $data, $url);
//        $res = json_decode($res,true);
//        $arr = json_decode(file_get_contents('http://localhost:5678/sidecar2/sidecar2/ad/info.php'),true);
//        array_unshift($res,$arr);
//        echo json_encode($res);
    }

    public function save()
    {
//        echo 'save';
        $order_id = $this->input->get_post('order_id');
        $this->load->model('my_order');
//        print_r($this->My_order);exit;
        $id = $this->my_order->insert_entry($order_id);
        echo '{"order_id": ' . $id . ', "error": 0}';
    }

    public function save2()
    {
        $order_id = $this->input->get_post('order_id');
        echo '{"order_id": ' . $order_id . ', "error": 0}';
    }

    public function save3()
    {
        $order_id = $this->input->get_post('order_id');
        for ($i = 0; $i < 10000; $i++) {
            md5($order_id);
        }
        echo '{"order_id": ' . $order_id . ', "error": 0}';
    }

    public function redis()
    {
        echo 'redis';
        $from = '127.0.0.1:6379/0';
        $to = '127.0.0.1:6379/1';
        $from_redis = redis_init($from);
        $to_redis = redis_init($to);

        $keys = $from_redis->keys('*');
        $count = 0;
        $total = count($keys);
        foreach ($keys as $key) {
            if (++$count % 100 == 1) {
                echo "$count/$total\n";
            }
            $type = $from_redis->type($key);
            switch ($type) {
                case Redis::REDIS_STRING:
                    $val = $from_redis->get($key);
                    $to_redis->set($key, $val);
                    break;
                case Redis::REDIS_LIST:
                    $list = $from_redis->lRange($key, 0, -1);
                    foreach ($list as $val) {
                        $to_redis->rPush($key, $val);
                    }
                    break;
                case Redis::REDIS_HASH:
                    $hash = $from_redis->hGetAll($key);
                    $to_redis->hMSet($key, $hash);
                    break;
                case Redis::REDIS_ZSET:
                    $zset = $from_redis->zRange($key, 0, -1, true);
                    foreach ($zset as $val => $score) {
                        $to_redis->zAdd($key, $score, $val);
                    }
                    break;
            }
        }


    }

    public function gen()
    {
        $from_redis = new Redis();
//        redis-cli -h 10.0.100.38 -a '(VPC2018C)'
//        $from_redis->connect('10.0.100.38', 6379);
        $from_redis->connect('localhost', 6379);
//        $from_redis->auth('(VPC2018C)');
        $from_redis->select(0);

        // redis-cli -h 172.17.0.5 -a Sharing
        $to_redis = new Redis();
        $to_redis->connect('localhost', 6379);
//        $to_redis->auth('Sharing');
        $to_redis->select(1);
        $iterator = null;
        while ($keys = $from_redis->scan($iterator)) {
            foreach ($keys as $key) {
                echo $key . ':';
                $type = $from_redis->type($key);
                echo $type . ':';
                switch ($type) {
                    case Redis::REDIS_STRING:
                        $val = $from_redis->get($key);
                        echo $val . ':';
                        if ($to_redis->set($key, $val)) {
                            echo 'success' . PHP_EOL;
                        } else {
                            echo 'fail' . PHP_EOL;
                        }
                        break;
                    case Redis::REDIS_LIST:
                        $list = $from_redis->lRange($key, 0, -1);
                        foreach ($list as $val) {
                            $to_redis->rPush($key, $val);
                        }
                        break;
                    case Redis::REDIS_SET:
                        $set = $from_redis->sMembers($key);
                        foreach ($set as $val) {
                            $to_redis->sAdd($key, $val);
                        }
                        break;
                    case Redis::REDIS_ZSET:
                        $zset = $from_redis->zRange($key, 0, -1, true);
                        foreach ($zset as $val => $score) {
                            $to_redis->zAdd($key, $score, $val);
                        }
                        break;

                    case Redis::REDIS_HASH:
                        $hash = $from_redis->hGetAll($key);
                        $to_redis->hMSet($key, $hash);
                        break;
                }
            }
        }
    }
}

